package com.lqq.chapter07;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @Author lqq677
 * @Date 2021/8/11 19:56
 * @Description 6辆汽车，停 3个车位
 */
public class SemaphoreDemo {
    public static void main(String[] args) {

        //创建Semaphore对象，设置许可证
        Semaphore semaphore =new Semaphore(3);

        //模拟6辆汽车停车
        for (int i = 1; i <= 6; i++) {
            new Thread(() ->{
                try {

                    //抢车位
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+" 抢到了停车位");

                    //模拟停车的时间
                    Integer time = new Random().nextInt(5);
                    TimeUnit.SECONDS.sleep(time);

                    //驶出停车位
                    System.out.println(Thread.currentThread().getName()+" ---- 停了"+ time +"秒钟，现在驶出停车位" );
                    semaphore.release();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }, String.valueOf(i)).start();
        }

    }
}
